// outputconfigwidget.cpp
#include "outputconfigwidget.h"
#include "ui_outputconfigwidget.h"
#include <QDateTime>
#include <QMessageBox>
#include <QJsonDocument>
#include <QFile>
#include <QNetworkInterface>
#include <QTextStream>
#include <QDateTime>

outputConfigWidget::outputConfigWidget(QWidget *parent)
    : QWidget(parent), ui(new Ui::outputConfigWidget)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_StyledBackground); // 这句不加,样式表是加载不出来的
    ui->dateTimeEdit->setCurrentDateTime();
}

outputConfigWidget::~outputConfigWidget()
{
    delete ui;
}

// 从文件加载路由记录
void outputConfigWidget::loadRouteRecords()
{
    QFile file("config/routeRecord.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        // 文件不存在或无法打开，清空路由记录列表
        m_addedRoutes.clear();
        return;
    }

    QTextStream in(&file);
    m_addedRoutes.clear();

    while (!in.atEnd())
    {
        QString route = in.readLine().trimmed();
        if (!route.isEmpty())
        {
            m_addedRoutes.append(route);
        }
    }

    file.close();
}

// 保存路由记录到文件
void outputConfigWidget::saveRouteRecords()
{
    QFile file("config/routeRecord.txt");
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        emit signalToForward("Failed to save route records: " + file.errorString());
        return;
    }

    QTextStream out(&file);
    for (const QString &route : m_addedRoutes)
    {
        out << route << "\n";
    }

    file.close();
}

// 删除所有记录的路由
void outputConfigWidget::deleteAllRecordedRoutes()
{
    // 加载已记录的路由
    loadRouteRecords();

    // 删除所有记录的路由
    for (const QString &route : m_addedRoutes)
    {
        QString deleteRouteCmd = QString("route del %1").arg(route);
        int result = system(deleteRouteCmd.toStdString().c_str());
        qDebug() << "Delete route command:" << deleteRouteCmd << "Result:" << result;
    }

    // 清空路由记录
    m_addedRoutes.clear();
    saveRouteRecords();
}

// 管理主机路由
void outputConfigWidget::manageHostRoutes()
{
    // 收集所有需要的路由
    QStringList requiredRoutes;

    // 遍历所有tab页收集路由信息
    for (int i = 0; i < ui->tabWidget->count(); ++i)
    {
        remoteTab *tab = qobject_cast<remoteTab *>(ui->tabWidget->widget(i));
        if (tab)
        {
            QJsonObject parameters = tab->getParameters();
            // if (parameters["connectType"].toInt() == 1)
            // {
            //     QString host = parameters["serverIp"].toString();
            //     // 确保host不为空且是有效的IP地址或主机名
            //     if (!host.isEmpty() && host != "0.0.0.0" && !requiredRoutes.contains(host))
            //     {
            //         requiredRoutes.append(host);
            //     }
            // }
        }
    }

    // 加载已记录的路由
    loadRouteRecords();

    // 删除不再需要的路由
    for (const QString &route : m_addedRoutes)
    {
        if (!requiredRoutes.contains(route))
        {
            QString deleteRouteCmd = QString("route del %1").arg(route);
            int result = system(deleteRouteCmd.toStdString().c_str());
            qDebug() << "Delete route command:" << deleteRouteCmd << "Result:" << result;
        }
    }

    // 添加新的路由
    for (const QString &route : requiredRoutes)
    {
        if (!m_addedRoutes.contains(route))
        {
            // 获取当前网络设备的网关信息
            QString currentDevice;
            QString gateway;

            if (ui->cb_connectType && ui->cb_connectType->currentIndex() >= 0)
            {
                currentDevice = ui->cb_connectType->currentText();
            }

            if (!currentDevice.isEmpty() && m_networkConfigs.contains(currentDevice))
            {
                QJsonObject config = m_networkConfigs[currentDevice];
                gateway = config["gateway"].toString();
            }

            // 构造添加路由的命令
            QString addRouteCmd;
            if (!currentDevice.isEmpty())
            {
                // 如果有网卡信息，则指定网卡
                if (!gateway.isEmpty())
                {
                    // 如果有网关信息，则指定网关
                    addRouteCmd = QString("route add %1 gw %2 dev %3").arg(route).arg(gateway).arg(currentDevice);
                }
                else
                {
                    // 如果没有网关信息，则只指定网卡
                    addRouteCmd = QString("route add %1 dev %3").arg(route).arg(currentDevice);
                }
            }
            else
            {
                // 如果没有网卡信息
                if (!gateway.isEmpty())
                {
                    // 如果有网关信息，则指定网关
                    addRouteCmd = QString("route add %1 gw %2").arg(route).arg(gateway);
                }
                else
                {
                    // 如果既没有网卡也没有网关信息，则只添加目标IP
                    addRouteCmd = QString("route add %1").arg(route);
                }
            }

            int result = system(addRouteCmd.toStdString().c_str());
            qDebug() << "Add route command:" << addRouteCmd << "Result:" << result;
        }
    }

    // 更新路由记录
    m_addedRoutes = requiredRoutes;
    saveRouteRecords();
}

// outputconfigwidget.cpp 中修改 processJsonCommand 函数
bool outputConfigWidget::processJsonCommand(const QString &jsonStr, QString *err)
{
    // 检查是否是初始化命令
    if (!initialized)
    {
        initializeFromRemoteJson();
        initialized = true;
    }
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(jsonStr.toUtf8(), &error);

    if (error.error != QJsonParseError::NoError)
    {
        emit signalToForward("JSON analyse failed: " + error.errorString());
        return false;
    }

    QJsonObject root = doc.object();

    // 检查是配置还是数据
    bool isConfig = root.contains("plugin_config");
    bool isData = root.contains("plugin_data");

    if (!isConfig && !isData)
    {
        emit signalToForward("JSON format error: can not find plugin_config or plugin_data segment");
        return false;
    }

    QString rootSection = isConfig ? "plugin_config" : "plugin_data";
    QJsonObject configObj = root[rootSection].toObject();
    // 解析权限信息（如果存在）
    if (configObj.contains("permission") && configObj["permission"].isString() && isConfig == true)
    {
        QString permissionStr = configObj["permission"].toString();
        bool ok;
        int permission = permissionStr.toInt(&ok);
        if (ok)
        {
            m_permissionLevel = permission;
            qDebug() << "Permission level updated to:" << permission;
            if (permission == 0)
            {
                ui->frame->setEnabled(false);
                ui->frame_2->setEnabled(false);
                ui->frame_3->setEnabled(false);
                ui->frame_4->setEnabled(false);
            }
            else
            {
                ui->frame->setEnabled(true);
                ui->frame_2->setEnabled(true);
                ui->frame_3->setEnabled(true);
                ui->frame_4->setEnabled(true);
            }
        }
    }
    // 处理blocks数据
    if (configObj.contains("blocks") && configObj["blocks"].isArray())
    {
        QJsonArray blocksArray = configObj["blocks"].toArray();

        // 如果是配置消息，清空并重新构建map
        if (isConfig)
        {
            m_modbusDataMap.clear();
        }

        // 遍历所有block，提取点位信息
        for (const QJsonValue &blockValue : blocksArray)
        {
            if (!blockValue.isObject())
                continue;

            QJsonObject blockObj = blockValue.toObject();

            // 处理parameters
            if (blockObj.contains("parameters") && blockObj["parameters"].isArray())
            {
                QJsonArray paramsArray = blockObj["parameters"].toArray();

                // 提取点位信息，以modbusAddr为key，data为value
                for (const QJsonValue &paramValue : paramsArray)
                {
                    if (paramValue.isObject())
                    {
                        QJsonObject paramObj = paramValue.toObject();
                        QString modbusAddr = paramObj["modbusAddr"].toString();
                        QString data = paramObj["data"].toString();

                        if (isConfig)
                        {
                            // 配置消息：添加或更新条目
                            m_modbusDataMap[modbusAddr] = data;
                        }
                        else if (isData)
                        {
                            // 数据消息：只更新现有条目的值
                            if (m_modbusDataMap.contains(modbusAddr))
                            {
                                m_modbusDataMap[modbusAddr] = data;
                            }
                        }
                    }
                }
            }
        }
    }

    // 更新所有 tab 的数据映射 - 使用常量引用传递避免拷贝
    for (int i = 0; i < ui->tabWidget->count(); ++i)
    {
        remoteTab *tab = qobject_cast<remoteTab *>(ui->tabWidget->widget(i));
        if (tab)
        {
            tab->updateModbusDataMap(m_modbusDataMap);
        }
    }

    return true;
}

void outputConfigWidget::initializeFromRemoteJson()
{
    // 首先应用启动时的网络配置
    // applyNetworkConfigOnStartup();
    // 首先获取本机可用的网卡设备
    m_networkDevices = getAvailableNetworkDevices();

    QFile file("config/remote.json");
    if (!file.open(QIODevice::ReadOnly))
    {
        emit signalToForward("Failed to open remote.json: " + file.errorString());
        return;
    }

    QByteArray jsonData = file.readAll();
    file.close();

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(jsonData, &parseError);

    if (parseError.error != QJsonParseError::NoError)
    {
        emit signalToForward("Failed to parse remote.json: " + parseError.errorString());
        return;
    }

    QJsonObject root = doc.object();
    if (!root.contains("plugin_remote"))
    {
        emit signalToForward("plugin_remote section not found in remote.json");
        return;
    }

    QJsonObject pluginRemote = root["plugin_remote"].toObject();

    // 加载网络配置
    loadNetworkConfigs(pluginRemote);

    // 应用加载的网络配置
    applyLoadedNetworkConfigs();

    // 获取默认网卡设备
    QString defaultNetworkDevice;
    if (pluginRemote.contains("network_device") && pluginRemote["network_device"].isString())
    {
        defaultNetworkDevice = pluginRemote["network_device"].toString();
    }

    // 检查默认网卡是否在可用网卡列表中
    bool defaultDeviceAvailable = m_networkDevices.contains(defaultNetworkDevice);

    // 如果默认网卡不可用且有可用网卡，则使用第一个网卡
    if ((!defaultDeviceAvailable || defaultNetworkDevice.isEmpty()) && !m_networkDevices.isEmpty())
    {
        defaultNetworkDevice = m_networkDevices.first();
    }

    // 更新UI中的网卡选择
    if (ui->cb_connectType)
    {
        ui->cb_connectType->clear();
        ui->cb_connectType->addItems(m_networkDevices);
        if (!defaultNetworkDevice.isEmpty())
        {
            int index = ui->cb_connectType->findText(defaultNetworkDevice);
            if (index >= 0)
            {
                ui->cb_connectType->setCurrentIndex(index);
            }
        }
    }

    // 更新网络配置显示
    updateNetworkConfigDisplay(defaultNetworkDevice);

    if (!pluginRemote.contains("tabs") || !pluginRemote["tabs"].isArray())
    {
        return;
    }

    QJsonArray tabsArray = pluginRemote["tabs"].toArray();

    // 清空现有标签页（如果有）
    while (ui->tabWidget->count() > 0)
    {
        QWidget *widget = ui->tabWidget->widget(0);
        ui->tabWidget->removeTab(0);
        delete widget;
    }

    // 根据JSON数据创建标签页
    for (const QJsonValue &tabValue : tabsArray)
    {
        if (!tabValue.isObject())
            continue;

        QJsonObject tabObject = tabValue.toObject();
        QString tabTitle = tabObject["tabTitle"].toString();

        if (tabObject.contains("parameters") && tabObject["parameters"].isObject())
        {
            QJsonObject parameters = tabObject["parameters"].toObject();

            // 确定最大寄存器地址
            int maxRegisterAddress = 1100; // 默认值
            if (!m_modbusDataMap.isEmpty())
            {
                // 查找最大的寄存器地址
                for (auto it = m_modbusDataMap.begin(); it != m_modbusDataMap.end(); ++it)
                {
                    bool ok;
                    int address = it.key().toInt(&ok);
                    if (ok && address > maxRegisterAddress)
                    {
                        maxRegisterAddress = address + 1;
                    }
                }
            }
            maxRegisterAddress = qMax(maxRegisterAddress, 1100);

            // 创建新的remoteTab
            remoteTab *newRemoteTab = new remoteTab(tabTitle, maxRegisterAddress, this);
            // 设置网络设备列表
            newRemoteTab->setNetworkDevices(m_networkDevices);
            newRemoteTab->setNetworkConfigs(m_networkConfigs);
            newRemoteTab->setParameters(parameters);
            // 添加到tabWidget
            int tabIndex = ui->tabWidget->addTab(newRemoteTab, tabTitle);

            // 连接信号槽
            connect(newRemoteTab, &remoteTab::tabNameChanged,
                    this, &outputConfigWidget::onTabNameChanged);
        }
    }

    emit signalToForward("Initialized from remote.json successfully");

    // 管理主机路由
    manageHostRoutes();
}

void outputConfigWidget::on_pb_addTab_clicked()
{
    // 生成标签标题
    QString tabTitle = QString("平台 %1").arg(ui->tabWidget->count() + 1);

    // 确定最大寄存器地址
    int maxRegisterAddress = 1100; // 默认值
    if (!m_modbusDataMap.isEmpty())
    {
        // 查找最大的寄存器地址
        for (auto it = m_modbusDataMap.begin(); it != m_modbusDataMap.end(); ++it)
        {
            bool ok;
            int address = it.key().toInt(&ok);
            if (ok && address > maxRegisterAddress)
            {
                maxRegisterAddress = address + 1;
            }
        }
    }
    maxRegisterAddress = qMax(maxRegisterAddress, 1100);

    // 创建一个新的 remoteTab 实例，传入标签标题和最大寄存器地址
    remoteTab *newRemoteTab = new remoteTab(tabTitle, maxRegisterAddress, this);

    // 设置网络设备列表
    newRemoteTab->setNetworkDevices(m_networkDevices);
    newRemoteTab->setNetworkConfigs(m_networkConfigs);
    // 将新创建的 remoteTab 添加为 tabWidget 的新标签页
    int tabIndex = ui->tabWidget->addTab(newRemoteTab, tabTitle);

    // 连接信号槽，用于更新标签标题
    connect(newRemoteTab, &remoteTab::tabNameChanged,
            this, &outputConfigWidget::onTabNameChanged);

    // 可选：设置新添加的标签为当前活动标签
    ui->tabWidget->setCurrentIndex(tabIndex);

    // 更新路由配置
    // manageHostRoutes();
}

void outputConfigWidget::on_pb_deleteTab_clicked()
{
    // 获取当前选中的标签页索引
    int currentIndex = ui->tabWidget->currentIndex();

    // 检查是否有选中的标签页
    if (currentIndex >= 0)
    {
        // 弹出确认对话框
        QMessageBox::StandardButton reply;
        reply = QMessageBox::question(this, "确认删除", "确定要删除当前标签页吗？",
                                      QMessageBox::Yes | QMessageBox::No);

        // 如果用户选择不删除，则直接返回
        if (reply != QMessageBox::Yes)
        {
            return;
        }

        // 获取当前标签页的widget
        QWidget *currentWidget = ui->tabWidget->widget(currentIndex);

        // 从tabWidget中移除该标签页
        ui->tabWidget->removeTab(currentIndex);

        // 删除对应的widget以释放内存
        if (currentWidget)
        {
            delete currentWidget;
        }

        // 可选：如果删除后没有标签页了，可以添加默认行为
        if (ui->tabWidget->count() == 0)
        {
            // 例如添加一个默认标签页或禁用某些控件
        }

        // 更新路由配置
        // manageHostRoutes();
    }
    else
    {
        // 可选：如果没有选中的标签页，可以显示提示信息
        emit signalToForward("没有选中的标签页");
    }
}

void outputConfigWidget::onTabNameChanged(const QString &name)
{
    // 获取发送信号的对象
    remoteTab *senderTab = qobject_cast<remoteTab *>(sender());
    if (!senderTab)
        return;

    // 查找该对象在 tabWidget 中的索引
    for (int i = 0; i < ui->tabWidget->count(); ++i)
    {
        if (ui->tabWidget->widget(i) == senderTab)
        {
            // 更新对应标签的标题
            QString newTitle = name.isEmpty() ? "未命名" : name;
            ui->tabWidget->setTabText(i, newTitle);
            break;
        }
    }
}

// outputconfigwidget.cpp
void outputConfigWidget::on_pb_saveTab_clicked()
{
    // 获取所有参数
    QJsonObject allParams = getAllParameters();

    // 创建完整的JSON对象
    QJsonObject root;
    root["plugin_remote"] = allParams;

    // 生成JSON文档
    QJsonDocument doc(root);

    // 参考config_addstyle.cpp的保存方式，使用相同的路径保存remote.json
    QFile file("config/remote.json");
    if (file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        file.write(doc.toJson());
        file.close();

        // 添加提示框询问是否重启以生效配置，参考config_addstyle.cpp的方式
        QMessageBox msgBox(this);
        msgBox.setWindowTitle("配置已保存");
        msgBox.setText("配置已保存成功！是否重启生效？");
        msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        msgBox.setButtonText(QMessageBox::Yes, "是");
        msgBox.setButtonText(QMessageBox::No, "否");
        if (msgBox.exec() == QMessageBox::Yes)
        {
            // 发送重启信号或执行重启操作
            emit signalToForward("remote.json updated");
        }
        // else
        // {
        //     // 保存后更新路由
        //     manageHostRoutes();
        // }
    }
    else
    {
        emit signalToForward("Failed to save remote.json: " + file.errorString());
    }
}

void outputConfigWidget::loadNetworkConfigs(const QJsonObject &pluginRemote)
{
    if (pluginRemote.contains("network_configs") && pluginRemote["network_configs"].isObject())
    {
        QJsonObject networkConfigs = pluginRemote["network_configs"].toObject();

        for (auto it = networkConfigs.begin(); it != networkConfigs.end(); ++it)
        {
            // 只有当网卡在本机存在时才加载配置
            if (it.value().isObject() && m_networkDevices.contains(it.key()))
            {
                m_networkConfigs[it.key()] = it.value().toObject();
            }
        }
    }
}

void outputConfigWidget::applyLoadedNetworkConfigs()
{
    // 遍历所有已加载的网络配置
    for (auto it = m_networkConfigs.begin(); it != m_networkConfigs.end(); ++it)
    {
        QString deviceName = it.key();
        QJsonObject config = it.value();

        // 应用静态IP配置
        QString localIp = config["local_ip"].toString();
        QString subnetMask = config["subnet_mask"].toString();
        QString gateway = config["gateway"].toString();

        // 设置静态IP和子网掩码
        if (!localIp.isEmpty() && !subnetMask.isEmpty())
        {
            QString ifconfigCommand = QString("ifconfig %1 %2 netmask %3")
                                          .arg(deviceName)
                                          .arg(localIp)
                                          .arg(subnetMask);

            int result = system(ifconfigCommand.toStdString().c_str());
            if (result == 0)
            {
                emit signalToForward(QString("Applied IP configuration for %1").arg(deviceName));
                qDebug() << "Successfully applied IP configuration for" << deviceName;
            }
            else
            {
                emit signalToForward(QString("Failed to apply IP configuration for %1").arg(deviceName));
                qDebug() << "Failed to apply IP configuration for" << deviceName;
            }

            // 如果有网关配置，则添加默认路由
            if (!gateway.isEmpty())
            {
                QString routeCommand = QString("route add default gw %1 dev %2")
                                           .arg(gateway)
                                           .arg(deviceName);

                int routeResult = system(routeCommand.toStdString().c_str());
                if (routeResult == 0)
                {
                    emit signalToForward(QString("Added default route via %1 for %2").arg(gateway, deviceName));
                    qDebug() << "Successfully added default route via" << gateway << "for" << deviceName;
                }
                else
                {
                    emit signalToForward(QString("Failed to add default route via %1 for %2").arg(gateway, deviceName));
                    qDebug() << "Failed to add default route via" << gateway << "for" << deviceName;
                }
            }
        }
    }
}

void outputConfigWidget::saveNetworkConfigs(QJsonObject &pluginRemote) const
{
    // 保存网络设备列表
    QJsonArray devicesArray;
    for (const QString &device : m_networkDevices)
    {
        devicesArray.append(device);
    }
    pluginRemote["network_devices"] = devicesArray;

    // 保存网络配置
    QJsonObject networkConfigs;
    for (auto it = m_networkConfigs.begin(); it != m_networkConfigs.end(); ++it)
    {
        networkConfigs[it.key()] = it.value();
    }
    pluginRemote["network_configs"] = networkConfigs;
}

QStringList outputConfigWidget::getAvailableNetworkDevices()
{
    QStringList deviceNames;
    m_networkConfigs.clear();

    // 获取可用的网络接口
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    for (const QNetworkInterface &interface : interfaces)
    {
        // 跳过本地回环设备
        if (interface.flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            continue;
        }
        // 通过名称过滤点对点(P2P)类型的网卡
        QString deviceName = interface.name();
        // 过滤常见的P2P接口名称
        if (deviceName.startsWith("ppp") ||     // PPP接口
            deviceName.startsWith("sl") ||      // SLIP接口
            deviceName.startsWith("tun") ||     // TUN接口
            deviceName.startsWith("tap") ||     // TAP接口
            deviceName.startsWith("wmaster") || // 无线主接口
            deviceName.contains("usb") ||       // USB网络接口（某些情况下）
            deviceName.startsWith("wwan") ||    // WWAN接口
            deviceName.startsWith("mon") ||     // WWAN接口
            deviceName.startsWith("p2p") ||     // WWAN接口
            deviceName.startsWith("rmnet"))     // Android RmNet接口
        {
            continue;
        }
        if (interface.flags().testFlag(QNetworkInterface::IsUp) &&
            interface.flags().testFlag(QNetworkInterface::IsRunning))
        {
            QString deviceName = interface.name();
            deviceNames << deviceName;

            // 初始化网卡配置为本机实际信息
            QJsonObject deviceConfig;
            QString localIp, subnetMask;

            // 获取该接口的地址信息
            QList<QNetworkAddressEntry> addressEntries = interface.addressEntries();
            for (const QNetworkAddressEntry &entry : addressEntries)
            {
                // 我们通常关心IPv4地址
                if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol)
                {
                    localIp = entry.ip().toString();
                    subnetMask = entry.netmask().toString();
                    break;
                }
            }

            deviceConfig["local_ip"] = localIp;
            deviceConfig["gateway"] = ""; // 网关信息不容易直接获取
            deviceConfig["subnet_mask"] = subnetMask;
            m_networkConfigs[deviceName] = deviceConfig;
        }
    }

    return deviceNames;
}

QJsonObject outputConfigWidget::getAllParameters() const
{
    QJsonObject result;
    QJsonArray tabsArray;

    // 遍历所有tab页
    for (int i = 0; i < ui->tabWidget->count(); ++i)
    {
        QJsonObject tabObject;

        // 获取tab标题
        tabObject["tabTitle"] = ui->tabWidget->tabText(i);

        // 获取tab中的remoteTab对象
        remoteTab *tab = qobject_cast<remoteTab *>(ui->tabWidget->widget(i));
        if (tab)
        {
            // 获取该tab的所有参数
            tabObject["parameters"] = tab->getParameters();
        }

        tabsArray.append(tabObject);
    }

    result["tabs"] = tabsArray;
    result["tabCount"] = tabsArray.size();

    // 保存网络配置
    saveNetworkConfigs(result);

    // 保存当前选中的网络设备
    if (ui->cb_connectType && ui->cb_connectType->currentIndex() >= 0)
    {
        QString currentDevice = ui->cb_connectType->currentText();
        result["network_device"] = currentDevice;
    }

    return result;
}

void outputConfigWidget::on_cb_connectType_currentIndexChanged(int index)
{
    if (index >= 0 && ui->cb_connectType)
    {
        QString selectedDevice = ui->cb_connectType->itemText(index);
        updateNetworkConfigDisplay(selectedDevice);
    }
}

void outputConfigWidget::updateNetworkConfigDisplay(const QString &deviceName)
{
    QString localIp, gateway, subnetMask;

    // 首先尝试从配置文件中读取网络配置
    if (!deviceName.isEmpty() && m_networkConfigs.contains(deviceName))
    {
        QJsonObject config = m_networkConfigs[deviceName];
        localIp = config["local_ip"].toString();
        gateway = config["gateway"].toString();
        subnetMask = config["subnet_mask"].toString();
    }
    // 如果配置文件中没有该网卡的配置，则获取本机实际的网卡信息
    else if (!deviceName.isEmpty())
    {
        // 获取本机该网卡的信息
        QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
        for (const QNetworkInterface &interface : interfaces)
        {
            if (interface.name() == deviceName)
            {
                // 获取该接口的地址信息
                QList<QNetworkAddressEntry> addressEntries = interface.addressEntries();
                for (const QNetworkAddressEntry &entry : addressEntries)
                {
                    // 我们通常关心IPv4地址
                    if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol)
                    {
                        localIp = entry.ip().toString();
                        gateway = ""; // 网关信息不容易直接获取
                        subnetMask = entry.netmask().toString();
                        break;
                    }
                }
                break;
            }
        }
    }

    // 更新UI显示
    if (ui->le_localIp)
        ui->le_localIp->setText(localIp);
    if (ui->le_gateway)
        ui->le_gateway->setText(gateway);
    if (ui->le_broadcast)
        ui->le_broadcast->setText(subnetMask);
}

void outputConfigWidget::on_pb_netSave_clicked()
{
    // 获取当前选中的网卡设备
    QString currentDevice;
    if (ui->cb_connectType)
    {
        int currentIndex = ui->cb_connectType->currentIndex();
        if (currentIndex >= 0)
        {
            currentDevice = ui->cb_connectType->currentText();
        }
    }

    // 如果没有选中网卡，则直接返回
    if (currentDevice.isEmpty())
    {
        QMessageBox::warning(this, "警告", "未选择网卡设备");
        return;
    }

    // 获取当前UI中的网络配置信息
    QString localIp, gateway, subnetMask;
    if (ui->le_localIp)
        localIp = ui->le_localIp->text();
    if (ui->le_gateway)
        gateway = ui->le_gateway->text();
    if (ui->le_broadcast)
        subnetMask = ui->le_broadcast->text();

    // 更新当前设备的配置（使用UI中的最新值）
    if (m_networkConfigs.contains(currentDevice))
    {
        QJsonObject currentDeviceConfig = m_networkConfigs[currentDevice];
        currentDeviceConfig["local_ip"] = localIp;
        currentDeviceConfig["gateway"] = gateway;
        currentDeviceConfig["subnet_mask"] = subnetMask;
        m_networkConfigs[currentDevice] = currentDeviceConfig;
    }

    // 读取现有的remote.json文件
    QFile file("config/remote.json");
    if (!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::critical(this, "错误", "无法打开 remote.json: " + file.errorString());
        emit signalToForward("Failed to open remote.json: " + file.errorString());
        return;
    }

    QByteArray jsonData = file.readAll();
    file.close();

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(jsonData, &parseError);

    if (parseError.error != QJsonParseError::NoError)
    {
        QMessageBox::critical(this, "错误", "解析 remote.json 失败: " + parseError.errorString());
        return;
    }

    QJsonObject root = doc.object();
    if (!root.contains("plugin_remote"))
    {
        QMessageBox::critical(this, "错误", "remote.json 中缺少 plugin_remote 节点");
        return;
    }

    QJsonObject pluginRemote = root["plugin_remote"].toObject();

    // 更新network_device为当前选中的设备
    pluginRemote["network_device"] = currentDevice;

    // 保存所有本机网卡的配置
    QJsonObject networkConfigs;
    for (auto it = m_networkConfigs.begin(); it != m_networkConfigs.end(); ++it)
    {
        networkConfigs[it.key()] = it.value();
    }
    pluginRemote["network_configs"] = networkConfigs;

    // 保存网络设备列表
    QJsonArray devicesArray;
    for (const QString &device : m_networkDevices)
    {
        devicesArray.append(device);
    }
    pluginRemote["network_devices"] = devicesArray;

    // 将更新后的pluginRemote写回root
    root["plugin_remote"] = pluginRemote;

    // 写入文件
    QJsonDocument newDoc(root);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QMessageBox::critical(this, "错误", "无法写入 remote.json: " + file.errorString());
        return;
    }

    file.write(newDoc.toJson());
    file.close();

    // 生成当前选中网卡的ifconfig指令
    if (!localIp.isEmpty() && !subnetMask.isEmpty())
    {
        QString ifconfigCommand = QString("ifconfig %1 %2 netmask %3")
                                      .arg(currentDevice)
                                      .arg(localIp)
                                      .arg(subnetMask);

        qDebug() << "网络配置命令: " << ifconfigCommand;
        int result = system(ifconfigCommand.toStdString().c_str());

        // 判断网络设置是否成功
        if (result == 0)
        {
            QMessageBox::information(this, "成功", "网络配置已成功应用到 " + currentDevice);
            emit signalToForward("Network configuration applied successfully for " + currentDevice);
        }
        else
        {
            QString errorMsg = QString("网络配置应用失败，请检查参数是否正确\n"
                                       "命令: %1\n"
                                       "返回码: %2")
                                   .arg(ifconfigCommand)
                                   .arg(result);
            QMessageBox::critical(this, "失败", errorMsg);
            emit signalToForward("Failed to apply network configuration for " + currentDevice);
        }
    }
    else
    {
        QMessageBox::warning(this, "警告", "IP地址或子网掩码不能为空");
    }
}

void outputConfigWidget::applyNetworkConfigOnStartup()
{
    QFile file("config/remote.json");
    if (!file.open(QIODevice::ReadOnly))
    {
        emit signalToForward("Failed to open remote.json for startup config: " + file.errorString());
        return;
    }

    QByteArray jsonData = file.readAll();
    file.close();

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(jsonData, &parseError);

    if (parseError.error != QJsonParseError::NoError)
    {
        emit signalToForward("Failed to parse remote.json for startup config: " + parseError.errorString());
        return;
    }

    QJsonObject root = doc.object();
    if (!root.contains("plugin_remote"))
    {
        emit signalToForward("plugin_remote section not found in remote.json for startup config");
        return;
    }

    QJsonObject pluginRemote = root["plugin_remote"].toObject();

    // 获取网络配置
    if (pluginRemote.contains("network_configs") && pluginRemote["network_configs"].isObject())
    {
        QJsonObject networkConfigs = pluginRemote["network_configs"].toObject();

        for (auto it = networkConfigs.begin(); it != networkConfigs.end(); ++it)
        {
            QString deviceName = it.key();
            QJsonObject config = it.value().toObject();

            // 跳过本地回环设备
            if (deviceName.startsWith("lo"))
            {
                continue;
            }

            QString localIp = config["local_ip"].toString();
            QString subnetMask = config["subnet_mask"].toString();
            QString gateway = config["gateway"].toString();

            // 设置静态IP和子网掩码
            if (!localIp.isEmpty() && !subnetMask.isEmpty())
            {
                QString ifconfigCommand = QString("ifconfig %1 %2 netmask %3")
                                              .arg(deviceName)
                                              .arg(localIp)
                                              .arg(subnetMask);

                int result = system(ifconfigCommand.toStdString().c_str());
                if (result == 0)
                {
                    emit signalToForward(QString("Applied IP configuration for %1").arg(deviceName));
                }
                else
                {
                    emit signalToForward(QString("Failed to apply IP configuration for %1").arg(deviceName));
                }

                // 如果有网关配置，则添加路由
                if (!gateway.isEmpty())
                {
                    QString routeCommand = QString("route add default gw %1 dev %2")
                                               .arg(gateway)
                                               .arg(deviceName);

                    int routeResult = system(routeCommand.toStdString().c_str());
                    if (routeResult == 0)
                    {
                        emit signalToForward(QString("Added default route via %1 for %2").arg(gateway, deviceName));
                    }
                    else
                    {
                        emit signalToForward(QString("Failed to add default route via %1 for %2").arg(gateway, deviceName));
                    }
                }
            }
        }
    }
}

void outputConfigWidget::on_pb_timeSave_clicked()
{
    // 弹出确认对话框
    QMessageBox msgBox(this);
    msgBox.setWindowTitle("确认修改系统时间");
    msgBox.setText(QString("确定要将系统时间修改为:\n%1").arg(ui->dateTimeEdit->dateTime().toString("yyyy-MM-dd hh:mm:ss")));
    msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    msgBox.setButtonText(QMessageBox::Yes, "确认修改");
    msgBox.setButtonText(QMessageBox::No, "取消");
    msgBox.setDefaultButton(QMessageBox::No);

    // 如果用户选择确认修改
    if (msgBox.exec() == QMessageBox::Yes)
    {
        // 格式化时间字符串为Linux date命令格式
        QString timeString = ui->dateTimeEdit->dateTime().toString("yyyy-MM-dd hh:mm:ss");

        // 构建修改系统时间的命令
        QString dateCommand = QString("date -s \"%1\"").arg(timeString);

        // 执行修改系统时间的命令
        int result = system(dateCommand.toStdString().c_str());

        if (result == 0)
        {
            // 同步硬件时钟
            system("hwclock --systohc");

            QMessageBox::information(this, "成功", "系统时间已成功修改为:\n" + timeString);
            emit signalToForward("System time updated to: " + timeString);
        }
        else
        {
            QMessageBox::critical(this, "失败", "修改系统时间失败，请检查权限设置");
            emit signalToForward("Failed to update system time");
        }
    }
    else
    {
        // 用户取消修改，恢复原来的时间
        QDateTime currentTime = QDateTime::currentDateTime();
        ui->dateTimeEdit->setDateTime(currentTime);
        qDebug() << "用户取消修改系统时间，恢复为当前时间:" << currentTime;
    }
}

void outputConfigWidget::on_pb_databaseEmpty_clicked()
{
    // 弹出确认对话框
    QMessageBox msgBox(this);
    msgBox.setWindowTitle("确认清空数据库");
    msgBox.setText("确定要清空数据库吗？\n此操作将删除所有历史数据且无法恢复。");
    msgBox.setInformativeText("数据库将在下次程序启动时被清空");
    msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    msgBox.setButtonText(QMessageBox::Yes, "确认清空");
    msgBox.setButtonText(QMessageBox::No, "取消");
    msgBox.setDefaultButton(QMessageBox::No);
    msgBox.setIcon(QMessageBox::Warning);

    // 如果用户选择确认清空
    if (msgBox.exec() == QMessageBox::Yes)
    {
        // 创建标记文件，指示下次启动时应删除数据库
        QFile flagFile("delete_database.flag");
        if (flagFile.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            QTextStream out(&flagFile);
            out << "This file indicates that databases should be deleted on next startup.\n";
            out << "Files to delete:\n";
            out << "warning.db\n";
            out << "sqliteTemp_test.db\n";
            flagFile.close();

            QMessageBox::information(this, "标记成功",
                                     "数据库将在下次程序启动时被清空。\n"
                                     "请重启程序以完成操作。");
        }
        else
        {
            QMessageBox::critical(this, "失败",
                                  "无法创建删除标记文件，请检查权限设置");
        }
    }
    else
    {
        // 用户取消操作
        qDebug() << "用户取消清空数据库操作";
    }
}
